import logging,datetime,traceback
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from day1.tools.my_log import MyLog
log = MyLog()

class BasePage():

    def __init__(self, driver):
        # self.driver = webdriver.Chrome()
        self.driver = driver


    def get_element(self, locator, doc=''):
        log.info("元素定位")
        try:
            ele = self.driver.find_element(*locator)
            return ele
        except Exception as e:
            print(traceback.format_exc(e))
            self.get_screen_shot(doc)
            log.debug("定位失败!!!")


    def input_text(self, locator, text, doc=''):
        log.info('{0}输入操作{1}'.format(doc, locator))
        try:
            ele = self.get_element(locator)
            ele.send_keys(text)
            log.info("输入操作成功")
        except Exception as e:
            print(traceback.format_exc(e))
            self.get_screen_shot(doc)
            log.info("输入操作失败")

    def click_element(self, locator, doc=''):
        log.info('{0}点击操作{1}'.format(doc,locator))
        try:
            ele = self.get_element(locator)
            ele.click()
            log.info("点击操作成功")
        except Exception as e:
            print(traceback.format_exc(e))
            self.get_screen_shot(doc)
            log.info("点击操作失败")

    def wait_element_is_visible(self, locator, timeout=10, poll=0.5, doc=""):
        """

        :param locator:
        :param timeout:
        :param poll:
        :param doc: 模块名_页面名_操作名
        :return:
        """
        log.info("等待元素{0}可见".format(doc))
        try:
            start_time = datetime.datetime.now()  # 获取当前时间
            WebDriverWait(self.driver, timeout, poll).until(EC.visibility_of_all_elements_located(locator))
            end_time = datetime.datetime.now()
            times = (end_time-start_time).seconds
            log.info('等待成功,等待时间为{0}'.format(times))
        except:
            log.info('{0}等待失败!!!'.format(doc))
            self.get_screen_shot(doc)

    def get_screen_shot(self, doc=''):
        filename = '../test_result/images/'+'{0}.png'.format(doc)
        self.driver.get_screenshot_as_file(filename)


# if __name__ == '__main__':
#     driver = webdriver.Chrome()
#     driver.get_screenshot_as_file('../test_result/images/test_a.png')